package com.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.CategoryVo;
import com.app.vo.IncidentVo;
import com.app.vo.RoleVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@Controller
@RequestMapping("/api/inc")
public class IncidentController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private IncidentService incidentService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private PersonService personService;

    @GetMapping("/getDropList")//下拉框查询
    public Result<Object> getDropList(
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }

        CategoryVo vo = new CategoryVo();

        List<CategoryModel> categoryModelList = categoryService.getCategoryByPid(25);
        vo.setEventTypeList(categoryModelList);//事件类型
        return Result.success(vo);
    }

    @GetMapping("/warnNumber")//警示条数
    public Result<Object> getWarnNumber(
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.success(0);
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        List<IncidentModel> incidentModels = incidentService.selectAll(user.getDepartmentId());
        int count = 0;
        for (int i = 0; i < incidentModels.size(); i++) {
            Integer warnTime = incidentModels.get(i).getWarnTime();
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime minusDays = now.minusDays(warnTime);
            LocalDateTime createTime = incidentModels.get(i).getCreateTime();
            if (minusDays.isBefore(createTime)) {
                count++;
            }
        }
        return Result.success(count);
    }

    @GetMapping("/getIncList")//事件管理分页查询
    public Result<Object> getIncList(
            @RequestParam("page") Integer page,
            @RequestParam("limit") Integer limit,
            @RequestParam(required = false) String eventName,
            @RequestParam(required = false) Integer eventType,
            Integer sortType,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        List<Integer> idList = departmentService.getDepId(user.getDepartmentId());
        Page<IncidentModel> incModelPage = incidentService.getPageIciList(page, limit, eventName, eventType, idList,sortType);
        for (int i = 0; i < incModelPage.getRecords().size(); i++) {
            if (incModelPage.getRecords().get(i).getDepartmentId() != null) {
                DepartmentModel departmentModel = departmentService.getDepByDepId(incModelPage.getRecords().get(i).getDepartmentId());
                if (departmentModel != null) {
                    incModelPage.getRecords().get(i).setDepartmentText(departmentModel.getName());
                }
            }
            if (incModelPage.getRecords().get(i).getLevel()!=null) {
                CategoryModel categoryById = categoryService.getCategoryById(incModelPage.getRecords().get(i).getLevel());
                incModelPage.getRecords().get(i).setLevelText(categoryById.getName());
            }
        }
        int count = (int) incModelPage.getTotal();
        List<IncidentModel> IncModelList;
        IncModelList = incModelPage.getRecords();
        IncidentVo vo = new IncidentVo();
        vo.setCount(count);
        vo.setList(IncModelList);
        return Result.success(vo);
    }

    //重点警示添加
    @PostMapping("/insertInc")
    public Result<Object> insertInc(@RequestBody IncidentModel incidentModel, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        try {
            if (incidentModel.getId() > 0) {
                incidentModel.setUpdateTime(LocalDateTime.now());
                incidentService.update(incidentModel);
            } else {
                incidentModel.setCreateTime(LocalDateTime.now());
                incidentService.insert(incidentModel);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return Result.success(null);
    }

    @GetMapping("/deleteById")//删除事件
    public Result<Object> deleteById(@RequestParam("id") Integer id, HttpServletRequest request) {
        // 校验token并获取用户信息
        AdminUserModel user = validateTokenAndGetUser(request);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }

        // 获取事件信息并进行删除操作
        IncidentModel incidentModel = incidentService.getIciByIncId(id);
        if (incidentModel == null) {
            return Result.error(500, "该事件不存在");
        }

        incidentService.delete(id);
        return Result.success(null);
    }



    @DeleteMapping("/deleteIncidentBatchByIds")
    public Result<Object> deleteBatchByIds(@RequestParam("ids") String ids, HttpServletRequest request){
        // 校验token并获取用户信息
        AdminUserModel user = validateTokenAndGetUser(request);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        return  incidentService.deleteIncidentBatchByIds(ids);
    }


    // 校验token并获取用户信息的方法
    private AdminUserModel validateTokenAndGetUser(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            throw new IllegalArgumentException("token不存在");
        }
        String userId = TokenUtils.verify(token);
        return adminUserService.getUserByUserId(Integer.parseInt(userId));
    }

}
